<!--
 * @Author: suo.tianbao suo.tianbao@vpclub.cn
 * @Date: 2023-10-11
 * @LastEditors: suo.tianbao suo.tianbao@vpclub.cn
 * @LastEditTime: 2023-10-11
 * @FilePath: /element-admin/src/views/aliyun/VpProduct.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div id="HealthyCateringMatching-page">
    <!--顶部搜索栏-->
    <div class="col-md-12">
      <el-row :gutter="20">
        <el-col :span="22" :offset="1" class="clearfix">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span style="font-size: 22px;">A.计算基础数据 </span>
                <el-button type="info" class="register_btn" size="small" @click.native="cal_Body_Fat">计算</el-button>
              </div>
            </template>
            <el-form :model="HealthCM" label-width="140px">
              <el-row :gutter="10">
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="年龄">
                    <el-input v-model="HealthCM.age" placeholder="年龄" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="性别">
                    <el-select v-model="HealthCM.sex" placeholder="性别" size="small" @change="handle_loadCoefficient">
                      <el-option label="请选择性别" value=-1></el-option>
                      <el-option :label="item.label" :value=item.value :data="item" v-for="item in sex_options"
                                 v-bind:key="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="身高(m)">
                    <el-input v-model="HealthCM.height" placeholder="身高" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="体重(kg)">
                    <el-input v-model="HealthCM.weight" placeholder="体重" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="BMI">
                    <el-input v-model="HealthCM.BMI" placeholder="BMI" size="small" :clearable="true" readonly></el-input>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="体脂率(m)">
                    <el-input v-model="HealthCM.bodyFatRat" placeholder="体脂率(m)" size="small" :clearable="true" readonly></el-input>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="生物静态系数">
                    <el-input v-model="HealthCM.staticCoefficient " placeholder="生物静态系数" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :sm="5" :xs="5" :md="5" :lg="5" :xl="5">
                  <el-form-item label="生物动态系数">
                    <el-input v-model="HealthCM.dynamicCoefficient" placeholder="生物动态系数" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :sm="8" :xs="8" :md="8" :lg="8" :xl="8">
                  <el-form-item label="摄入热量(卡路里)">
                    <el-input v-model="HealthCM.calories" placeholder="卡路里" size="small" :clearable="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!--中部数据表格栏-->
    <div class="col-md-12" style="margin-top: 25px">
      <el-row :gutter="20">
        <el-col :span="22" :offset="1" class="clearfix">
          <el-card class="box-card" style="margin-bottom: 15px">
            <template #header>
              <div class="card-header">
                <span style="font-size: 22px;">B.食材配比计算 </span>
                <el-button type="info" class="register_btn" size="small" @click.native="handle_cal" v-if="claflg">计算</el-button>
                <el-button type="warning" class="register_btn" size="small" @click.native="handle_confirm" v-if="!claflg">确认</el-button>
              </div>
            </template>
            <div style="overflow:auto;overflow-x: hidden">
              <el-table :header-cell-style="{background: '#eef1f6', color:'#606266'}"
                        :data="tableData" :cell-style="{padding:'3px'}"
                        :row-style="{height:'30px'}" :max-height="tableHeight"
                        :key="isIndex" style="width: 100%" v-loading="isLoading" border stripe row-key="id">
                <el-table-column fixed type="index" label="序号" width="85px" v-show="false"></el-table-column>
                <el-table-column fixed prop="classification" label="食材类别" width="120px"/>
                <el-table-column fixed prop="classification" label="食材选择阈值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.count" placeholder="食材选择数量" size="small" :clearable="true"
                              @change.native="(val) => cal_DailyTake(val,'count',scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column fixed prop="combinationRatio" label="组合配比(%)">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.combinationRatio" placeholder="配比" size="small" :clearable="true"
                              @change.native="(val) => cal_DailyTake(val,'combinationRatio',scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column fixed prop="standardUnit" label="标准单位(克)" v-if="false">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.standardUnit" placeholder="配比" size="small" :clearable="true"
                              @change.native="(val) => cal_DailyTake(val,'standardUnit',scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column fixed prop="totalDailyIntake" label="日摄入总量(克)">
                  <template slot-scope="scope">
                    {{ scope.row.totalDailyIntake }}
                  </template>
                </el-table-column>
                <el-table-column fixed prop="calories" label="卡路里(J)" v-if="false"/>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="col-md-12" style="margin-top: 25px">
      <el-row :gutter="20">
        <el-col :span="22" :offset="1" class="clearfix">
          <div style="overflow:auto;overflow-x: hidden" v-loading.fullscreen.lock="fullscreenLoading">
            <!-- LEV 1 DATA-->
            <el-row v-for="(opt, index) in tableData2" v-bind:key="opt.key" style="margin-bottom: 25px">
              <el-col class="clearfix">
                <el-card :body-style="{ padding: '0px'}">
                  <template #header>
                    <div class="card-header">
                      <span style="font-size: 22px;">C.食材搭配方案 {{ index + 1 }} </span>
                      <el-button type="primary" class="register_btn" size="small" >选择方案</el-button>
                    </div>
                  </template>
                  <!--                    <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">-->
                  <!-- LEV 2 combinations-->
                  <el-row :gutter="5" v-for="opt2 in opt.combination" v-bind:key="opt2.id">
                    <el-col :span="22" :offset="1" class="clearfix">
                      <span style="font-weight: bold">{{ "[" + opt2.Classification + "]" }}</span>
                      <el-row :gutter="5" >
                        <el-col :span="10" :offset="index3 > 0 ? 1 : 0" class="clearfix" v-for="(opt3,index3) in opt2.FoodIngredients" v-bind:key="opt3.id">
                          <el-descriptions class="custRow" title="" :column="3" size="mini" border>
                            <el-descriptions-item :span="3">
                              <template slot="label"><i class="el-icon-mobile-phone"></i>食材品名</template>
                              {{ (index3+1)+'.'+opt3.name }}
                            </el-descriptions-item>
                            <el-descriptions-item>
                              <template slot="label"><i class="el-icon-mobile-phone"></i>日摄入量</template>
                              {{ opt3.totalDailyIntake }}
                            </el-descriptions-item>
                            <el-descriptions-item>
                              <template slot="label"><i class="el-icon-location-outline"></i>单品热量</template>
                              {{ opt3.calories }}
                            </el-descriptions-item>
                            <el-descriptions-item>
                              <template slot="label">
                                <i class="el-icon-tickets"></i>热量占比(%)
                              </template>
                              {{ opt3.combinationRatio }}
                            </el-descriptions-item>
                            <el-descriptions-item>
                              <template slot="label"><i class="el-icon-office-building"></i>所属标签</template>
                              <el-tag size="small">{{ opt3.classification }}</el-tag>
                            </el-descriptions-item>
                          </el-descriptions>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                  <div style="padding: 14px;">
                    <div class="bottom clearfix">
                      <span >{{ desp }}</span>
                      <time class="time" style="margin-left: 15px">{{ currentDate }}</time>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import {mapMutations} from "vuex";
import {calPairings, calFoodCatalogs} from "@/api/hcmvApi";
import {Message} from 'element-ui';

export default {
  name: "HealthyCateringMatchingView",
  components: {},
  data() {
    return {
      isIndex: 1,
      isLoading: false,
      fullscreenLoading: false,
      tableHeight: 650,
      HealthCM: {
        age: 33,
        sex: 1,
        weight: 77,
        height: 170,
        BMI: 0,
        bodyFatRat: 0,
        calories: 2000,
        calorGap:1500,
        staticCoefficient: 0,
        dynamicCoefficient: 0
      },
      sex_options: [
        {label: "男", value: 0, key: 0},
        {label: "女", value: 1, key: 1},
      ],
      claflg: false,
      calParam: [],
      calParamIdx: [],
      tableData: [],
      tableData2: [],
      currentDate: new Date(),
      desp: "",
    }
  },
  computed: {},
  methods: {
    ...mapMutations(['add_tab']),
    handle_init() {
      this.handle_loadCoefficient()
    },
    handle_loadCoefficient() {
      if (this.HealthCM.sex == "0") {
        //   男性系数
        this.HealthCM.staticCoefficient = 20;
        this.HealthCM.dynamicCoefficient = 3 / 100;
      } else {
        //   女性系数
        this.HealthCM.staticCoefficient = 18;
        this.HealthCM.dynamicCoefficient = 2 / 100
      }
    },
    handle_fetch() {
      this.tableData = [];
      calFoodCatalogs(this.HealthCM).then(res => {
        if (res.code == 200) {
          this.isLoading = false;
          this.tableData = res.data;
          // Message.success("参数核算完成")
          this.$notify({
            title: '通知',
            message: '食材配比数据读取完成',
            type: 'success',
            offset: 100
          });
        }
      }).catch(err => {
        // Message.error('错了哦，STEP 1 参数异常' + err);
        this.$notify({
          title: '执行失败',
          message: '错了哦，计算参数异常' + err,
          type: 'error',
          offset: 100
        });
      })
    },
    handle_confirm(){
      let load_rows = this.tableData;
      if (load_rows.length == 0){
        this.$notify({
          title: '计算失败',
          message: '请先计算基础数据',
          type: 'warning',
          offset: 100
        });
        return
      }
      load_rows.forEach((element) => {
        this.calParamIdx.push(element.id);
        this.calParam.push({
          "id": element.id,
          "classification": element.classification,
          "combinationRatio": element.combinationRatio,
          "count": element.count,
          "totalDailyIntake": element.totalDailyIntake
        });
      })
      // console.log(JSON.stringify(this.calParam));
      this.claflg =true;
    },
    handle_cal() {
      if (!this.claflg){
        this.$notify({
          title: '计算失败',
          message: '确认食材配比方案',
          type: 'warning',
          offset: 100
        });
        return
      }
      this.tableData2 = [];
      this.fullscreenLoading = true;
      calPairings({params: this.calParam}).then(res => {
        if (res.code == 200) {
          this.tableData2 = res.data.list;
          this.currentDate = res.data.currentDate;
          this.desp = res.data.desp;
          this.fullscreenLoading = false;
          this.$notify({
            title: '通知',
            message: '配餐参数核算完成',
            offset: 100
          });
        }
      }).catch(err => {
        Message.error('错了哦，STEP 1 参数异常' + err);
      })
    },
    cal_Body_Fat() {
      // IF(P2=0,0,O2/(POWER(P2,2)))
      let cal_h = this.HealthCM.height / 100;
      let cal_w = this.HealthCM.weight;
      let BMI = (cal_w / (cal_h * cal_h));
      this.HealthCM.BMI = this.formattedNumber(BMI)
      // =(1.2*N2)+(0.23*$D$2)-16.2
      let FAT = (1.2 * this.HealthCM.BMI) + (0.23 * cal_w) - 16.2;
      // 调整计算公式 总消耗（打卡/焦）动态消耗值+静态消耗值
      // 动态消耗值=静态消耗值*动态系数
      // 静态消耗值=静态系数*体重
      let loss_A = this.HealthCM.weight * this.HealthCM.staticCoefficient
      let loss_B = loss_A * this.HealthCM.dynamicCoefficient
      this.HealthCM.bodyFatRat = this.formattedNumber(FAT);
      this.HealthCM.calories = loss_A + loss_B
      if (this.HealthCM.calories == 0) {
        this.$notify({
          title: '参数异常',
          message: '输入参数核验失败，请选择性别确认热量计算系数，生物静态系数，生物动态系数',
          type: 'warning',
          offset: 100
        });
        return;
      }
      this.handle_fetch();
    },
    cal_DailyTake(val, flg, row) {
      let res = parseFloat(this.HealthCM.calories) * parseFloat(row.combinationRatio / 100) * parseInt(row.standardUnit);
      row.totalDailyIntake = this.formattedNumber(res);
      let add_flg = true;
      let rpl_index = 0;
      for (let _index = 0; _index < this.calParamIdx.length; _index++) {
        let item = this.calParamIdx[_index];
        if (item == row.id) {
          add_flg = false;
          rpl_index = _index;
          break;
        }
      }
      if (add_flg) {
        this.calParamIdx.push(row.id);
        this.calParam.push({
          "id": row.id,
          "classification": row.classification,
          "combinationRatio": row.combinationRatio,
          "count": row.count,
          "totalDailyIntake": row.totalDailyIntake
        });
      } else {
        this.calParam[rpl_index] = {
          "id": row.id,
          "classification": row.classification,
          "combinationRatio": row.combinationRatio,
          "count": row.count,
          "totalDailyIntake": row.totalDailyIntake
        }
      }
      this.claflg = true;
    },
    formattedNumber(number) {
      const num = parseFloat(number); // 先将传入的值转换成浮点数类型
      if (!isNaN(num)) { // 判断是否能正常转换成数字
        return num.toFixed(2).toString(); // 返回保留两位小数后的结果
      } else {
        return ''; // 若传入值无法转换成数字，则返回空字符串
      }
    }
  }
  ,
  created() {
    this.handle_init();
  }
  ,
  mounted() {
  }
  ,
}
</script>
<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custRow {
  /*display: flex;*/
  margin-top: 5px;
  margin-bottom: 5px;
  padding: 5px 5px 5px 5px;
}

.time {
  font-size: 9px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>